package com.luo.demo.oidc.session.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.session.web.http.HttpSessionIdResolver;

/**
 * @author jitendra on 3/3/16.
 */
@Configuration
public class SessionConfig implements BeanClassLoaderAware {

	private ClassLoader loader;

	/**
	 * 设置Redis Json序列化
	 * @return
	 */
	@Bean
	public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
		return new GenericJackson2JsonRedisSerializer(objectMapper());
	}

	/**
	 * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default
	 * constructors
	 * @return the {@link ObjectMapper} to use
	 */
	private ObjectMapper objectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));
		return mapper;
	}

	/**
	 * @see org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang.ClassLoader)
	 */
	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.loader = classLoader;
	}

	///**
	// * 自定义Cookie序列化
	// */
	//@Bean
	//public CookieSerializer cookieSerializer() {
	//	DefaultCookieSerializer serializer = new DefaultCookieSerializer();
	//	serializer.setCookieName("JSESSIONID");
	//	//serializer.setCookiePath("/");
	//	//serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
	//	return serializer;
	//}
	//
	////HttpSessionId配置
	//@Bean
	//public HttpSessionIdResolver httpSessionIdResolver(){
	//	CookieHttpSessionIdResolver cookieHttpSessionIdResolver = new CookieHttpSessionIdResolver();
	//	cookieHttpSessionIdResolver.setCookieSerializer(cookieSerializer());
	//	return cookieHttpSessionIdResolver;
	//}


	/**
	 * 注册Session事件发布器
	 * @return
	 */
	@Bean
	public HttpSessionEventPublisher httpSessionEventPublisher() {
		return new HttpSessionEventPublisher();
	}


}
